package com.example.crm.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.example.crm.mapper.UserMapper;
import com.example.crm.pojo.UserExample;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

@WebServlet("/checkname")
public class CheckNameServlet extends HttpServlet {

	SqlSessionFactory sqlSessionFactory;

	// 每次执行测试前 要执行的代码
	public CheckNameServlet()
	{
		// 1. 创建SqlSessionFactoryBuilder对象
		SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

		// 2. 加载SqlMapConfig.xml配置文件
		InputStream inputStream;
		try {
			inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		// 3. 创建SqlSessionFactory对象
		this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
	}


	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw = resp.getWriter();
		
		// 1. 获取用户请求信息
		String username = req.getParameter("username");
		
//		try {
//			Thread.sleep(5000);
//		} catch (InterruptedException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
		
		// 2. 调用dao
		SqlSession sqlSession = sqlSessionFactory.openSession();
		UserMapper dao = sqlSession.getMapper(UserMapper.class);
		long result = 0;
		UserExample userExample = new UserExample();
		userExample.createCriteria().andUsernameEqualTo(username);
		result = dao.countByExample(userExample);

		
		// 3. 
		// 方式二 使用fastjson生成
		Map<String,Object> m = new HashMap<>();
		m.put("result", result);
		pw.print(JSONObject.toJSONString(m));
		
		// 方式一 自己打印一个json字符串
//		pw.print("{\"result\":"+result+"}");
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
